package cn.jbolt.ec.wx;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.jbolt.base.JBoltBaseController;
import cn.jbolt.common.model.BecMember;
import cn.jbolt.common.model.BecRetailer;
import cn.jbolt.common.model.BecRetailerStaff;
import cn.jbolt.common.model.BecSpreader;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.core.NotAction;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import java.util.ArrayList;
import java.util.List;

public class EcWechatController extends JBoltBaseController {
    @Inject
    CommonService commonService;
    @Inject
    MsgService msgService;
    @Inject
    QrcodeService qrcodeService;
    @Inject
    SubscribeService subscribeService;

    WxMpService wxMpService = GenService.getWxMpService("jmd");
    public void handle(){
        String signature = get("signature","no");
        String timestamp = get("timestamp","no");
        String nonce = get("nonce","no");
        String echostr = get("echostr","dammn");


        if(getRequest().getMethod().toUpperCase().equals("GET")){

            renderText(auth(signature,timestamp,nonce,echostr));

        }else{

            String openid = get("openid");
            System.out.println(openid);


            WxMpUser user= commonService.user_info(openid);
            String nickname = user.getNickname();


            if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
                throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
            }
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(getRawData());
            if (inMessage.getMsgType().equals("voice")||inMessage.getMsgType().equals("image")||inMessage.getMsgType().equals("video")){
                renderText(msgService.text_msg("未知类型的消息",inMessage).toXml());
                return;
            }

            if (inMessage.getMsgType().equals("text")) {
                renderText(msgService.text_msg("文字消息",inMessage).toXml());
                return;

            } else if (inMessage.getEvent().equals("subscribe")){
                if (inMessage.getEventKey().length() == 0) {  //用户不扫二维码直接点击
                    renderText(SubscribeService.me.handle_no_para(openid,nickname,inMessage));
                    return;
                } else {    //用户扫分销码关注
                     renderText(SubscribeService.me.handle_with_para_unconcerned(openid,nickname,inMessage,wxMpService));
                     return;
                }  //用户之前已关注扫分销码

            } else if (inMessage.getEvent().equals("SCAN")) {
                renderText(SubscribeService.me.handle_with_para_concerned(inMessage,openid,wxMpService));
                return;
            }else if (inMessage.getMsgType().equals("event") ) {
                String key = inMessage.getEventKey();

                if(key!=null && key.equals("V_1001")){
                    System.out.println("ts1016");

                    BecSpreader sp = new BecSpreader().dao().findFirst("select member_id,media_id,media_url,name " +
                            " from bec_spreader where audited=1 and member_id in (select id from bec_member where openid_jmd= ? )",inMessage.getFromUser());
                    if(sp!=null){
                        String media_id = sp.getMediaId();
                        String url = sp.getMediaUrl();
                        if(media_id==null || media_id.length()<5){
                            WxMpMaterialUploadResult res =qrcodeService.getSpreaderQrcodeMediaId(
                                    sp.getMemberId(),inMessage.getFromUser());

                            if(res==null) renderText("");
                            sp.setMediaId(res.getMediaId());
                            sp.setMediaUrl(res.getUrl());
                            sp.update();
                        }
                        HttpUtil.post(
                                "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + subscribeService.getAccessToken(),
                                msgService.spreader_json(openid,sp.getMediaUrl(),sp.getName()));

                        WxMpXmlOutMessage outMessage = (msgService.text_msg("转发到朋友圈或发给朋友", inMessage));
                        renderText(outMessage.toXml());
                        return;
                    }else{
                        WxMpXmlOutMessage outMessage = (msgService.text_msg("你不是分销商", inMessage));
                        renderText(outMessage.toXml());
                        return;
                    }
                }
            return;
            }
            System.out.println(inMessage.toString());
            renderText(msgService.text_msg("未知类型的消息",inMessage).toXml());

        }
    }

    public void init_menu(){
        WxMenu menu = new WxMenu();
        WxMenuButton button1=new WxMenuButton();
        button1.setType("view"); //点击事件按钮
        button1.setName("共享商城");
        button1.setUrl("https://ecb.foxcodes.cn/shop/index.html");


        WxMenuButton button3=new WxMenuButton();
        button3.setName("我的分销");
        button3.setType("click");
        button3.setKey("V_1001");


        WxMenuButton button2=new WxMenuButton();
        button2.setName("商家平台");
        button2.setType("view");
        button2.setUrl("https://ecb.foxcodes.cn/retailer/index.html");


        List<WxMenuButton> buttons=new ArrayList<WxMenuButton>();
        buttons.add(button1);

        buttons.add(button3);
        buttons.add(button2);


        menu.setButtons(buttons);
        try {
            wxMpService.getMenuService().menuCreate(menu);
            renderJson("{ok:0}");
        } catch (WxErrorException e) {
            // TODO Auto-generated catch block
            renderJson("{ok:1}");
            e.printStackTrace();
        }
    }

    @NotAction
    public String auth(String signature,String timestamp,
                       String nonce, String echostr){

        return echostr;

    }

    public void auth_by_code(String code){
        WxMpUser user= commonService.auth_by_code(code);
        BecMember becMember= new BecMember();
        BecMember member= becMember.findFirst("select id,openid_jmd from bec_member where openid_jmd=?",user.getOpenId());

        setSessionAttr("openSession",SecureUtil.md5(user.getOpenId()+System.currentTimeMillis()));

        setSessionAttr(getSessionAttr("openSession")+"_member_id",member.getId());

        setSessionAttr(getSessionAttr("openSession")+"_openid",user.getOpenId());

        JSONObject jo=new JSONObject();
        jo.put("user",user);
        jo.put("member_id",member.getId());
        BecRetailerStaff staff=new BecRetailerStaff();
        BecRetailerStaff retailerStaff= staff.findFirst("select * from bec_retailer_staff where openid=?",user.getOpenId());
        if (null==retailerStaff){
            setSessionAttr(getSessionAttr("openSession")+"_retailer_id",0);
            jo.put("retailer_id",0);
        }else {
            if (retailerStaff.getIsDel()){
                setSessionAttr(getSessionAttr("openSession")+"_retailer_id",0);
                jo.put("retailer_id",0);
            }else {
                setSessionAttr(getSessionAttr("openSession")+"_retailer_id",retailerStaff.getRetailerId());
                jo.put("retailer_id",retailerStaff.getRetailerId());
            }
        }
        BecSpreader becSpreader=new BecSpreader();
        BecSpreader spreader= becSpreader.findFirst("select member_id,audited from bec_spreader where member_id=?",member.getId());
        if (null==spreader){
            setSessionAttr(getSessionAttr("openSession")+"_spreader_judge",0);
            jo.put("spreader",0);
        }else {
            if (1==spreader.getAudited()){
                setSessionAttr(getSessionAttr("openSession")+"_spreader_judge",1);
                jo.put("spreader",1);
            }else {
                setSessionAttr(getSessionAttr("openSession")+"_spreader_judge",spreader.getAudited());
                jo.put("spreader",0);
            }
        }
        jo.put("openSession",getSessionAttr("openSession"));
        renderJson(jo);
    }



    public void user_info_by_openid(String openid){

        renderJson(commonService.user_info(openid));
    }

    public void js_sig(String url){


        try{
            WxJsapiSignature sig = wxMpService.createJsapiSignature(url);
            System.out.println(sig);
            renderJson(sig);
            return;


        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        renderJson("{ok:1}");


    }

}
